;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.DeliveryNotice", [])
        .controller("DeliveryNoticeCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", "$state", "$stateParams", function ($scope, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService, $state, $stateParams) {
            $scope.handleMaterialBlur = function (e) {
                $scope.condition.materialsNoList = UserContextService.MultiInput(e.target.value).split(',').filter(Boolean);
            };
            $scope.TJJXList = [];
            $scope.synCrmFlagStatus = {
                '-1':'同步失败',
                0:'未同步',
                1:'同步成功'
            }
            $scope.activeFlag = [true, false, false, false, false];
            $scope.detailFlag = [true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                allCheckedMaterialDetail: false,
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {
                isService :$scope.isTJ? $scope.curUser.isService:undefined
            };
            $scope.orderCondition = {
                status: 1
            };
            $scope.orderObj = {};
            $scope.dataList = [];
            $scope.outState = [
                {
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                },
                {
                    id: 3,
                    name: "强制完成"
                }
            ];
            $scope.reviewState = [
                {
                    id: 1,
                    name: "待审核"
                },
                {
                    id: 2,
                    name: "审核通过"
                },
                {
                    id: 3,
                    name: "审核拒绝"
                }
            ];
            $scope.returnState = [{
                    id: 0,
                    name: "未退货"
                },
                {
                    id: 1,
                    name: "退货中"
                },
                {
                    id: 2,
                    name: "退货完成"
                }
            ];
            $scope.reverseState = [{
                    id: 0,
                    name: "未冲销"
                },
                {
                    id: 1,
                    name: "待审核"
                },
                {
                    id: 2,
                    name: "审核通过"
                },
                {
                    id: 3,
                    name: "审核驳回"
                }
            ];
            $scope.orderDataList = [];
            $scope.selectedList = [];
            $scope.detailInfo = {
                sex: 1,
                locked: 0
            };
            $scope.deliveryStatues = [{
                id: 0,
                name: "已发货"
            }, {
                id: 1,
                name: "已签收"
            }];
            $scope.tabFlag = {};
            $scope.stepList = {
                curStep: 0,
                list: [{
                    name: '选择销售意向单'
                }, {
                    name: '生成发货通知单'
                }]
            };
            $scope.deliveryWayList = [];
            $scope.settleTypeList = [];
            $scope.payConditionList = [];
            $scope.distributionChannelList = [];
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            //所属办事处
            $scope.aencyList=[];
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetails"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/deliveryNote/exportDetailsAll")
            };
            $scope.tableConfig = {
                fixedWidth: 300,
                scrollWidth: 1630,
                tableCol: [
                    {
                        type: "",
                        name: "单号",
                        dataField: "deliveryNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "收货人",
                        dataField: "receiverName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "收货人电话",
                        dataField: "receiverPhone",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "收货地址",
                        dataField: "address",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "销售意向单号",
                        dataField: "saleNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "purchaseNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购合同号",
                        dataField: "purchaseContractNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP关联单号",
                        dataField: "sapOutNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP销售订单",
                        dataField: "sapSaleOrder",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP外向交货单",
                        dataField: "sapOutBill",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP开票凭证",
                        dataField: "sapInvoiceNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件凭证",
                        dataField: "materialsNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算方式",
                        dataField: "settleTypeName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "总价",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShows",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "isOutDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "updateStateDateTime",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "退货状态",
                        dataField: "isReturnShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "冲销状态",
                        dataField: "isReverseShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否打印",
                        dataField: "isPrintShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算状态",
                        dataField: "checkStateShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "签收状态",
                        dataField: "signStateShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备货状态",
                        dataField: "readyStateShow",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 120,
                        isShow: $scope.isTJ,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "reviewStateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditUserName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShows",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditRemark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM同步状态",
                        dataField: "synCrmFlagShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "同步CRM失败信息",
                        dataField: "synCrmErrormsg",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: " 同步CRM返回结果",
                        dataField: "synCrmResult",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 400,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "开票状态",
                        dataField: "ticketStateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                ]
            };
            $scope.tableMaterialConfig = {
                scrollWidth: 1270,
                tableCol: [
                    {
                        type: "",
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "钢印号",
                        dataField: "stealNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false
                    },
                    {
                        type: "",
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    /* wangcan:需求2492 */
                    {
                        type: "",
                        name: "适用机型",
                        dataField: "machineModel",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "amountAfterAdjust",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "sendQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "sendQty",
                        sortType: "",
                    },
                    {
                        name: "本次发货",
                        dataField: "deliveryQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "deliveryQty",
                        sortType: "",
                        isInput: true,
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "unitPriceAfterAdjust",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已出库数",
                        dataField: "inventoryOutAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        sortField: 'inventoryOutAmount',
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "enableNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "alterReport",
                        sortField: "enableNum",
                        sortType: ""
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        clickFnDaChang: "dachangStock",
                        dataField: "totalStock",
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentionNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "intentionDetail",
                        sortField: 'intentionNum',
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "deliveryNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "deliveryDetail",
                        sortField: 'deliveryNum',
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "危险库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                        isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };
            $scope.outTbConf = {
                scrollWidth: 1560,
                tableCol: [{
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "amountAfterAdjust",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "sendQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "deliveryQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        isInput: true
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "unitPriceAfterAdjust",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "enableNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentionNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "intentionDetail",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "deliveryNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "deliveryDetail",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "危险库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: "",
                        input: true,
                        inputType: "func"
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };
            $scope.adjustTbConf = {
                scrollWidth: 1560,
                tableCol: [{
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "amountAfterAdjust",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "sendQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "sendQty",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "deliveryQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "deliveryQty",
                        sortType: "",
                        isInput: true,
                        inputType: "num"
                    },
                    {
                        type: "",
                        name: "已出库数量",
                        dataField: "inventoryOutAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "inventoryOutAmount",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "unitPriceAfterAdjust",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "enableNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "enableNum",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentionNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "intentionDetail",
                        sortField: "intentionNum",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "deliveryNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        clickFn: "deliveryDetail",
                        sortField: "deliveryNum",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "危险库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };
            $scope.detailTbConfig = {
                scrollWidth: 1270,
                tableCol: [
                    {
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "行号",
                        dataField: "lineNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件分类",
                        dataField: "materialsType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "钢印号",
                        dataField: "stealNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "默认储位",
                        dataField: "stockLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "适用机型",
                        dataField: "machineModel",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "订单总数",
                        dataField: "amountAfterAdjust",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "已发数量",
                        dataField: "sendQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "本次发货",
                        dataField: "deliveryQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单价",
                        dataField: "unitPriceAfterAdjust",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "已出库数",
                        dataField: "inventoryOutAmount",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "实际库存",
                        dataField: "enableNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "大厂库存",
                        width: 100,
                        dataField: "totalStock",
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "意向占用",
                        dataField: "intentionNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "发货占用",
                        dataField: "deliveryNum",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "安全库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "是否开票",
                        dataField: "invoiceFlagShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "危险库存",
                        dataField: "logState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "外销单价",
                        width: 100,
                        dataField: "exportPrice",
                        isShow: $scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "外销金额",
                        width: 100,
                        dataField: "totalExportPrice",
                        isShow: $scope.isJCHK, // 仅限进出口
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                        isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };

            $scope.receiptTableInfo = {
                tableConfig: {
                    scrollWidth: 750,
                    tableCol: [{
                            name: "单据编号",
                            dataField: "billNo",
                            width: 160,
                            isShow: true,
                            type: "click",
                            clickFn: "viewOrderDetail"
                        },
                        {
                            name: "单据类型",
                            dataField: "billSingleF",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "单据创建时间",
                            dataField: "billDateF",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单据总金额",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "已收金额",
                            dataField: "receivePrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "应收金额",
                            dataField: "remainPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "本次收款金额",
                            dataField: "checkPrice",
                            width: 120,
                            isShow: true
                        }
                    ]
                },
                dataList: [],
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },
                tdClick: function (item, fnType) {
                    switch (fnType) {
                        case "viewOrderDetail":
                            viewOrderDetail(item);
                            break;
                        default:
                            break;
                    }
                }
            };

            $scope.tbMaterStyle = {
                scrollLeft: {
                    left: $scope.tableMaterialConfig.fixedWidth + "px"
                }
            };

            var materialListOri = [];

            var btnPermissionCode = {
                deliveryNoticeAdd: window.ActionCode.deliveryNoticeAdd,
                deliveryNoticeDel: window.ActionCode.deliveryNoticeDel,
                deliveryNoticePrint: window.ActionCode.deliveryNoticePrint,
                deliveryNoticeOut: window.ActionCode.deliveryNoticeOut,
                deliveryNoticeEdit: window.ActionCode.deliveryNoticeEdit,
                deliveryNoticePost: window.ActionCode.deliveryNoticePost,
                deliveryNoticePostDel: window.ActionCode.deliveryNoticePostDel,
                mandatoryFinish: window.ActionCode.deliveryNoticeForceComplete,
                adjust: window.ActionCode.deliveryNoticeAdjust,
                settlement: window.ActionCode.deliveryNoticeBalance,
                deliveryNoticeReady: window.ActionCode.deliveryNoticeReady,
                deliveryRevoke: window.ActionCode.deliveryNoticeRevoke,
                deliveryAudit: window.ActionCode.deliveryAudit,
                deliveryTJSC: window.ActionCode.deliveryTJSC, // 判断是否验证默认储位 和 库存
                deliveryNoticeRevokeOut: window.ActionCode.deliveryNoticeRevokeOut,
                deliveryNoticeCRM: window.ActionCode.deliveryNoticeCRM,
            };

            $scope.btnPermission = {
                deliveryNoticeAdd: true,
                deliveryNoticeDel: true,
                deliveryNoticePrint: true,
                deliveryNoticeOut: true,
                deliveryNoticeEdit: true,
                deliveryNoticePost: true,
                deliveryNoticePostDel: true,
                mandatoryFinish: true,
                adjust: true,
                settlement: true,
                deliveryNoticeReady: true,
                deliveryRevoke: true,
                deliveryAudit: true,
                deliveryTJSC: true,
                deliveryNoticeRevokeOut: true,
                deliveryNoticeCRM: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            //后端查询接口新增两个字段：
            // unInboundFlag：当为1时，代表需要查询未完全入库的数据，当为0或null时则不处理
            // dateRange：此字段代表需要查询多少天未完成入库的数据，当第一个字段未1时必填
            $scope.fiveDaysUnInStore = function () {
                if($scope.condition.unInboundFlagParam){
                    $scope.condition.unInboundFlag=1;
                    $scope.condition.dateRange=5;
                }else{
                    $scope.condition.unInboundFlag=0;
                    $scope.condition.dateRange=null;
                }
            };
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    scrollLeftWidth: { width: $scope.tableConfig.fixedWidth + "px" },
                };
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.materialList.length; i < len; i++) {
                    if (!!$scope.detailInfo.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.materialList[i].isChecked && $scope.detailInfo.materialList[i].status != 2 && $scope.detailInfo.materialList[i].status != 3) {
                            $scope.detailInfo.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                });
            };

            // 导入
            $scope.importMateriel = function () {
                var param = {
                    name: "(零件)",
                    templateReqService: "device",
                    templateReqUrl: "/downloadFile/excelTemplate",
                    templateCondition: {
                        excelFileName: "PurchaseInboundMaterialImport.xls"
                    },
                    importReqService: "device",
                    importReqUrl: `/deliveryNote/importMaterialExcelForCreate?saleIntentionId=${curSelectId}`,
                    importErrorUrl: "",
                };
                ybWidget.ImportFile(param).then(function (data) {
                    var realNum;
                    angular.forEach(data, function (item) {
                        item.sendQty = item.informedAmount;
                        item.oldDeliveryNum = item.deliveryNum;
                        item.oldEnableNum = item.enableNum;
                        item.deliveryMax = Number((item.amountAfterAdjust - item.informedAmount).toFixed(3));
                        item.deliveryQty = item.inputQty || Number((item.amountAfterAdjust - item.informedAmount).toFixed(3));

                        // 挖机与农机 需要处理 数量问题
                        if ($scope.isWJ || $scope.isNJ) {
                            realNum = parseFloat(item.enableNum) - parseFloat(item.deliveryNum);
                            if (realNum <= 0) {
                                item.deliveryQty = 0;
                            } else if (item.deliveryQty > realNum) {
                                item.deliveryQty = realNum;
                            }
                        }

                        if (item.deliveryQty <= item.deliveryMax) {
                            checkItemStockStatus(item);
                        }
                        item.deliveryDate = +new Date();
                        pickingBillMaterialChange(item)
                    });
                    $scope.detailInfo.materialList = data;
                    materialListOri = angular.copy($scope.detailInfo.materialList);
                });
            };
            $scope.orderFiled = "";

            $scope.materialToSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                var sortFiled = config[index];
                $scope.orderFiled = sortFiled.sortField;
                if (sortType == "desc") {
                    $scope.orderFiled = "-" + sortFiled.sortField;
                }
                $scope.detailInfo.materialList = $filter("orderBy")($scope.detailInfo.materialList, $scope.orderFiled);
            };

            $scope.delMaterial = function (index) {
                $scope.detailInfo.materialList.splice(index, 1);
            };
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    allCheckedMaterialDetail: false,
                };
                $scope.tabFlag = {};
                $scope.detailInfo = {};
                $scope.stepList.curStep = 0;
                $scope.deliveryWayList = [];
                $scope.settleTypeList = [];
                $scope.payConditionList = [];
                $scope.detailFlag = [true];
                materialListOri = [];
                $scope.onlyShowHasStock.value = false;
            }

            function getOrderDataList(curPage) {
                $scope.markInfo.allCheckedMaterial = false;
                var service = "device";
                var reqUrl = "/saleIntention/list";
                var param = {};
                param.pageSize = $scope.orderPageInfo.pageSize;
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.orderPageInfo.curPage;
                param.filters = angular.copy($scope.orderCondition);
                param.filters.notDirect = 1;
                // 外向交货单创建的选择界面筛选掉已完成订单(deliveryListFlag=1表示需要筛选)
                param.filters.deliveryListFlag = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        angular.forEach($scope.selectedList, function (item1) {
                            if (item.deliveryNo == item1.deliveryNo) {
                                item.isChecked = true;
                            }
                        })
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };
            $scope.importGYAdd = function () {
                $scope.isImportAdd = true;
                var param = {
                    name: "(钢印号)",
                    templateReqService: "device",
                    templateReqUrl: "/materials/downloadMaterialsSteelSealNumImpExcel",
                    importReqService: "device",
                    importReqUrl: "/materials/MaterialsSteelSealNumImpExcel ",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    $scope.changeTab(0);
                });
            };

            function getDataList(curPage) {
                $scope.markInfo.allCheckedBill = false;
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/deliveryNote/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.isReturnShow = $filter("ProgressStatus")(item.isReturn, "returnState");
                        item.isReverseShow = $filter("ProgressStatus")(item.isReverse, "reverse");
                        item.checkStateShow = $filter("ProgressStatus")(item.checkState, "checkState");
                        item.isPrintShow = item.isPrint === 0 ? "否" : "是";
                        item.reviewStateShow =  $filter("ProgressStatus")(item.reviewState, "auditDeliveryNotice");
                        item.createDateShow = $filter("YbDate")(item.createDate);
                        item.createDateShows = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShows = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.updateStateDateTime = $filter("YbDate")(item.updateStateDate, 'yyyy-MM-dd HH:mm:ss');
                        item.signStateShow = item.isSign === 0 ? "未签收" : "已签收";
                        item.readyStateShow = item.isReady === 0 ? "备货中" : "已就绪";
                        item.synCrmFlagShow = $scope.synCrmFlagStatus[item.synCrmFlag];
                        item.ticketStateShow = $filter("ProgressStatus")(item.ticketState, "ticketState");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.detailTbConfig.tableCol, 'enableNum').isShow = !$scope.needHide;
                        viewDetail(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "intentionDetail":
                        intentionDetail(item);
                        break;
                    case "deliveryDetail":
                        deliveryDetail(item);
                        break;
                    case "dachangStock":
                        dachangStock(item);
                        break;
                    default:
                        break;
                }
            };

            function intentionDetail(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.IntentionDetail(param);
            }

            function deliveryDetail(item) {
                console.log("item:",item);
                console.log("$scope.detailInfo:",$scope.detailInfo);
                
                
                var param = {
                    materialsNo: item.materialsNo,
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation,
                    purchaseOrgName:$scope.detailInfo.headerInfo.purchaseOrgName,
                };
                if ($scope.activeFlag[4]) {
                    param.billNo = $scope.detailInfo.headerInfo.deliveryNo;
                }
                ybWidget.DeliveryDetail(param);
            }

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            $scope.orderSearch = function () {
                getOrderDataList();
            };
            var curSelectId = ''
            $scope.orderSelectSingle = function (orderId) {
                console.log("orderSelectSingle");
                
                curSelectId = orderId;
                $scope.stepList.curStep = 1;
                ybHttp.Get('device', '/saleIntention/itemByDeliveryNote', {
                    id: orderId
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var realNum;
                    angular.forEach(resp.value.materialList, function (item) {
                        item.sendQty = item.informedAmount;
                        item.oldDeliveryNum = item.deliveryNum;
                        item.oldEnableNum = item.enableNum;
                        item.deliveryMax = Number((item.amountAfterAdjust - item.informedAmount).toFixed(3));
                        item.deliveryQty = Number((item.amountAfterAdjust - item.informedAmount).toFixed(3));
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        // 塔机的为下拉框字典需要映射
                     if ($scope.isTJ) {
                        $scope.tableMaterialConfig.tableCol[8].dataField = 'machineModelName'
                        resp.value.materialList.forEach(item => {
                            item.machineModelName = item.machineModel ?  $scope.TJJXList.find(c => c.code == item.machineModel)?.name : ''
                        })
                    }
                        // 挖机与农机 需要处理 数量问题
                        if ($scope.isWJ || $scope.isNJ) {
                            realNum = parseFloat(item.enableNum) - parseFloat(item.deliveryNum);
                            if (realNum <= 0) {
                                item.deliveryQty = 0;
                            } else if (item.deliveryQty > realNum) {
                                item.deliveryQty = realNum;
                            }
                        }

                        if (item.deliveryQty <= item.deliveryMax) {
                            checkItemStockStatus(item);
                        }
                        item.deliveryDate = +new Date();
                        pickingBillMaterialChange(item)
                    });
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.headerInfo.intentionId = orderId;
                    $scope.detailInfo.headerInfo.delivery = resp.value.headerInfo.purchaseOrgId;
                    $scope.detailInfo.headerInfo.sold = resp.value.headerInfo.purchaseOrgId;
                    $scope.detailInfo.headerInfo.deliveryTypeName = resp.value.headerInfo.deliverTypeName;
                    $scope.detailInfo.headerInfo.deliveryTypeId = resp.value.headerInfo.deliverTypeId;
                    $scope.detailInfo.headerInfo.address = resp.value.headerInfo.receiveAddress;
                    $scope.detailInfo.headerInfo.note = resp.value.headerInfo.remark;
                    $scope.detailInfo.headerInfo.distributionChannelName = "内销";
                    $scope.detailInfo.headerInfo.payConditionName = "全款提货";
                    $scope.detailInfo.headerInfo.distributionTypeShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.distributionType, "distributionType");
                    $scope.detailInfo.headerInfo.contractBillNo = resp.value.headerInfo.contractNo;
                    $scope.detailInfo.headerInfo.ticketStateShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.ticketState, "ticketState");

                    materialListOri = angular.copy($scope.detailInfo.materialList);
                });
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                localStorage.setItem($scope.storageKey, JSON.stringify($scope.condition));
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {unInboundFlag:0,dateRange:null,unInboundFlagParam:false,isService :$scope.isTJ? $scope.curUser.isService:undefined};
            };

            function geBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                geBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                geBillIds();
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                getOrderDataList();
                $scope.changeTab(1);
            };

            $scope.batchSapPost = function () {
                const ids = $scope.dataList.filter(df=> df.isChecked && (df.isOut == 2 || df.isOut == 3)).map(dm=> dm.id);
                if (ids.length == 0) {
                    ybWidget.ShowMessage('请选择已出库或者强制完成的行');
                    return;
                }
                ybHttp.Get('device', '/deliveryNote/sapBatchPost', { ids }).then(function(resp) {
                    if (resp.code !== 0) {
                        if (resp.value && resp.value.length > 0) {
                            ybWidget.ShowMessage(resp.value.join(";<br/>"), MESG_TYPE.Error, { isHtml: true });
                        } else {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        }
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                })

            };

            $scope.sapPost = function (id, status) {
                var service = "device";
                var reqUrl = "/deliveryNote/sapPost";
                var param = {};
                param.id = id;

                if (status === '0') {
                    ybWidget.ShowMessage("确定要提前过账吗？", MESG_TYPE.Ask).then(function () {
                        ybHttp.Get(service, reqUrl, param).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        });
                    }, function () {

                    });
                } else {
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                }
            };

            $scope.sapRemove = function (id) {
                var service = "device";
                var reqUrl = "/deliveryNote/sapRemove";
                var param = {};
                param.id = id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.delData = function (delType, Id) {
                var service = "device";
                var reqUrl = "/deliveryNote/delete";
                var param = {};
                param.Ids = [];

                if (delType === "single") {
                    param.Ids.push(Id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked && $scope.dataList[i].isOut === '0') {
                            param.Ids.push($scope.dataList[i].id);
                        }
                    }
                }
                if (param.Ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.Ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };
            $scope.syncCrm = function (delType, Id) {
                var service = "device";
                var reqUrl = "/deliveryNote/syncCrmPartsSaleContract?";
                var param = {};
                param.Ids = [];

                if (delType === "single") {
                    param.Ids.push(Id);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked && $scope.dataList[i].synCrmFlag != '1') {
                            param.Ids.push($scope.dataList[i].id);
                        }
                    }
                }
                if (param.Ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要同步CRM的行');
                    return;
                }
                let idsStr = ''
                param.Ids.forEach( i => {
                    idsStr = idsStr + 'ids=' + i + '&'
                });
                // 把字符串最后一个&截取掉
                if (idsStr[idsStr.length - 1] == '&') {
                    idsStr = idsStr.substring(0, idsStr.length - 1)
                }
                reqUrl = reqUrl + idsStr
                ybWidget.ShowMessage("确定要同步CRM吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp.value.join(','), MESG_TYPE.Error);
                            getDataList();
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {
                })
            };
            $scope.mandatoryFinish = function (billNo, billId, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryNote/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                                $scope.detailInfo = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.handleDeliveryRevoke = function (item, { materialsNo, inventoryOutAmount }) {
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/warehouseInventory/deliveryRevoke";
                    var param = {
                        businessOrder: item.deliveryNo,
                        materialsNo: materialsNo ? materialsNo : null,
                        revokeNum: inventoryOutAmount
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item.id).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                                $scope.detailInfo = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };


            function refreshMaterial() {
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    if (item.deliveryQty <= item.deliveryMax) {
                        checkItemStockStatus(item);
                    }
                });
            }

            function filterMaterial() {
                var warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                var areaCode = $scope.detailInfo.headerInfo.outArea;
                var material = [];
                for (let materialListOriItem of materialListOri) {
                    if (!!materialListOriItem.stockLocationList && materialListOriItem.stockLocationList.length > 0) {
                        for (var j = 0, lenJ = materialListOriItem.stockLocationList.length; j < lenJ; j++) {
                            var mWarehouseCode = materialListOriItem.stockLocationList[j].warehouseCode;
                            var mLocationCode = materialListOriItem.stockLocationList[j].locationCode;
                            var mAreaCode = materialListOriItem.stockLocationList[j].areaCode;
                            if (warehouseCode === mWarehouseCode) {
                                if (!!areaCode && areaCode !== mAreaCode) {
                                    continue;
                                }
                                materialListOriItem.stockLocation = mLocationCode;
                                material.push(materialListOriItem);
                                break;
                            }
                        }
                    }
                }
                $scope.detailInfo.materialList = material;
            }

            function findDeliveryNumFunc() {
                var service = "device";
                var reqUrl = "/saleIntention/findDeliveryNum";
                var param = {};
                param.saleNo = $scope.detailInfo.headerInfo.saleNo;
                param.warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                param.areaCode = $scope.detailInfo.headerInfo.outArea;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    if (!resp.value) {
                        return;
                    }

                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        angular.forEach(resp.value, function (itemDetail) {
                            if (item.materialsNo === itemDetail.materialsNo) {
                                item.deliveryNum = itemDetail.deliveryNum;
                                item.enableNum = itemDetail.enableNum;
                                // 查询仓库库存时，记录一下
                                if (!param.areaCode) {
                                  item.oldWarehouse_deliveryNum = item.deliveryNum
                                  item.oldWarehouse_enableNum = item.enableNum
                                }

                                // 挖机与农机 需要处理 数量问题
                                if ($scope.isWJ || $scope.isNJ) {
                                    item.deliveryQty = item.deliveryMax;
                                    var realNum = parseFloat(item.enableNum) - parseFloat(item.deliveryNum);
                                    if (realNum <= 0) {
                                        item.deliveryQty = 0;
                                    } else if (item.deliveryQty > realNum) {
                                        item.deliveryQty = realNum;
                                    }
                                }
                            }
                        });
                    });
                });
            }

            var afterSelectWarehouseMaterialListOri = [];
            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector({needPermit:true}).then(async function (data) {
                    if (!!$scope.detailInfo.headerInfo.outArea && (data.areaCode !== $scope.detailInfo.headerInfo.outArea)) {
                        $scope.detailInfo.headerInfo.outArea = "";
                        $scope.detailInfo.headerInfo.sapOutArea = "";
                        angular.forEach(materialListOri, function (item) {
                            item.stockLocation = "";
                        });
                        $scope.detailInfo.materialList = angular.copy(materialListOri);
                    }
                    angular.forEach(materialListOri, function (item) {
                        item.isChecked = false;
                    });
                    $scope.markInfo.allCheckedMaterial = false;

                    if ($scope.detailInfo.headerInfo.outLocation != data.warehouseCode) {
                        $scope.detailInfo.materialList = angular.copy(materialListOri);
                        $scope.onlyShowHasStock.value = false;
                    }

                    $scope.detailInfo.headerInfo.outLocation = data.warehouseCode;
                    if (!$scope.btnPermission.deliveryTJSC) { // 没有该权限，验证默认储位
                        filterMaterial();
                    } else {
                        console.log('有塔机、随车权限，不过滤');
                    }
                    await findDeliveryNumFunc();
                    refreshMaterial();

                    afterSelectWarehouseMaterialListOri = angular.copy($scope.detailInfo.materialList);
                })
            };

            $scope.clearWarehouse = function () {
                $scope.onlyShowHasStock.value = false;

                angular.forEach(materialListOri, function (item) {
                    item.stockLocation = "";
                });
                $scope.detailInfo.materialList = angular.copy(materialListOri);

                $scope.detailInfo.headerInfo.outLocation = "";
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    item.deliveryNum = item.oldDeliveryNum;
                    item.enableNum = item.oldEnableNum;
                });

                refreshMaterial();
            };

            $scope.selectArea = function () {
                if (!$scope.detailInfo.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择发出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                ybWidget.DepotAreaSelector(param).then(async function (data) {
                    if ($scope.detailInfo.headerInfo.outArea != data.areaCode) {
                        $scope.detailInfo.materialList = angular.copy(afterSelectWarehouseMaterialListOri);
                        $scope.onlyShowHasStock.value = false;
                    }

                    $scope.detailInfo.headerInfo.outArea = data.areaCode;
                    $scope.detailInfo.headerInfo.sapOutArea = data.sapCode;
                    if (!$scope.btnPermission.deliveryTJSC) { // 没有该权限，验证默认储位
                        filterMaterial();
                    } else {
                      console.log('有塔机、随车权限，不过滤');
                    }
                    await findDeliveryNumFunc();

                    refreshMaterial();
                })
            };

            $scope.clearArea = function () {
                $scope.onlyShowHasStock.value = false;

                $scope.detailInfo.materialList = angular.copy(afterSelectWarehouseMaterialListOri);

                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach($scope.detailInfo.materialList, function (item) {
                  // 没有就不取
                  if (!item.oldWarehouse_deliveryNum && item.oldWarehouse_deliveryNum !== 0) {
                    item.deliveryNum = item.oldDeliveryNum;
                    item.enableNum = item.oldEnableNum;
                    return
                  }
                  item.deliveryNum = item.oldWarehouse_deliveryNum;
                  item.enableNum = item.oldWarehouse_enableNum;
                });
                refreshMaterial();
            };

            $scope.onlyShowHasStock = { value: false };
            var oriData = [];
            $scope.toggleShowHasStock = function(val) {
                if (val) {
                    oriData = angular.copy($scope.detailInfo.materialList);
                    $scope.detailInfo.materialList = $scope.detailInfo.materialList.filter(mf => mf.enableNum > 0);
                } else {
                    $scope.detailInfo.materialList = angular.copy(oriData);
                }
            };

            $scope.tdRKClick = function(item) {
                ybWidget.DataSelector({
                    title: '钢印号',
                    url: '/materials/listSealNum',
                    otherParams: {billNo: $scope.detailInfo.headerInfo.deliveryNo, materialsNo: item.materialsNo},
                    fields: [
                        {
                            name: '零件编号',
                            dataField: 'materialsNo',
                            width: "50%"
                        },
                        {
                            name: '钢印号',
                            dataField: 'steelSealNum',
                            width: "50%"
                        },
                    ],
                    isOnlyShow: true,
                })
            }
            $scope.selectSeal = function(item,index) {
                if (!$scope.detailInfo.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择发出仓库');
                    return
                }

                ybWidget.DataSelector({
                    title: '钢印号',
                    url: `/deliveryNote/listStealNo`,
                    otherParams: {warehouseCode: $scope.detailInfo.headerInfo.outLocation, materialsNo: item.materialsNo},
                    fields: [
                        {
                            name: '零件编号',
                            dataField: 'materialsNo',
                            width: "50%"
                        },
                        {
                            name: '钢印号',
                            dataField: 'stealNo',
                            width: "50%"
                        },
                    ],
                    isMultiSelect: true,
                }).then(res => {
                    item.stealNo = res.map(r => r.stealNo).filter(Boolean).join(',')
                })
            }

            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/deliveryNote/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    resp.value.headerInfo.distributionTypeShow = $filter("ProgressStatus")(resp.value.headerInfo.distributionType, "distributionType");
                    return resp.value;
                });
            }

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    angular.forEach(data.materialList, function (obj) {
                        obj.estimatedShippingDateShow = $filter("YbDate")(obj.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        obj.invoiceFlagShow = $filter("TrueOrFalse")(obj.invoiceFlag)
                        pickingBillMaterialChange(obj)
                    })
                    console.log(data)
                    if ($scope.isTJ) {
                        $scope.tableMaterialConfig.tableCol[8].dataField = 'machineModelName'
                        $scope.detailTbConfig.tableCol[8].dataField = 'machineModelName'
                        data.materialList.forEach(item => {
                            item.machineModelName = item.machineModel ?  $scope.TJJXList.find(c => c.code == item.machineModel)?.name : ''
                    })
                }
                    data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                    data.headerInfo.ticketStateShow = $filter("ProgressStatus")( data.headerInfo.ticketState, "ticketState");
                    $scope.detailInfo = data;
                    $scope.changeTab(2);
                });
            }

            function getAencyList() {
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var param = {
                    pCode: "Aency"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.aencyList = resp.value;
                })
            }

            // 初始化编辑时的备用库存数量
            function initDeliveryNums() {
                if ($scope.detailInfo.materialList.length <= 0) {
                  return;
                }
                getDeliveryNum({warehouseCode: null, areaCode: null})
                getDeliveryNum({areaCode: null})
            }

            // 更新库存数量
            function getDeliveryNum(condition) {
                var service = "device";
                var reqUrl = "/materials/findDeliveryNum";
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation,
                    areaCode: $scope.detailInfo.headerInfo.outArea,
                    materialsVOS: $scope.detailInfo.materialList.map(item => ({materialsNo: item.materialsNo})),
                };
                Object.assign(param, condition)
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    if (!resp.value) {
                        return;
                    }

                    // 无仓库参数，获取的是所有的
                    if (!param.warehouseCode) {
                        angular.forEach(materialListOri, function (item) {
                        angular.forEach(resp.value.materialsVOS, function (itemDetail) {
                            if (item.materialsNo === itemDetail.materialsNo) {
                                item.oldDeliveryNum = itemDetail.deliveryNum;
                                item.oldEnableNum = itemDetail.enableNum;
                            }
                        });
                        });
                        return;
                    }

                    // 当前仓库的
                    angular.forEach(materialListOri, function (item) {
                        angular.forEach(resp.value.materialsVOS, function (itemDetail) {
                            if (item.materialsNo === itemDetail.materialsNo) {
                                item.oldWarehouse_deliveryNum = itemDetail.deliveryNum;
                                item.oldWarehouse_enableNum = itemDetail.enableNum;
                            }
                        });
                    });
                })
            }

            $scope.editData = function (item) {
                $scope.markInfo.allCheckedMaterial = false;
                var service = "device";
                var reqUrl = "/deliveryNote/item";
                var param = {};
                param.id = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    console.log($scope.detailTbConfig)
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                    $scope.stepList.curStep = 1;
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.headerInfo.customerPurchaseNo = resp.value.headerInfo.customerPurchaseCode;
                    $scope.detailInfo.headerInfo.distributionTypeShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.distributionType, "distributionType");
                    $scope.detailInfo.headerInfo.ticketStateShow = $filter("ProgressStatus")($scope.detailInfo.headerInfo.ticketState, "ticketState");
                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        item.deliveryMax = item.amountAfterAdjust - item.sendQty;
                        if (item.deliveryQty <= item.deliveryMax) {
                            checkItemStockStatus(item);
                        }
                        if ($scope.isTJ) {
                            $scope.tableMaterialConfig.tableCol[8].dataField = 'machineModelName'
                            $scope.detailTbConfig.tableCol[8].dataField = 'machineModelName'
                            resp.value.materialList.forEach(item => {
                                item.machineModelName = item.machineModel ?  $scope.TJJXList.find(c => c.code == item.machineModel)?.name : ''
                        })
                        }
                        pickingBillMaterialChange(item)
                    });
                    materialListOri = angular.copy($scope.detailInfo.materialList);
                    // 初始化编辑时的备用库存数量
                    initDeliveryNums();
                });
            };

            $scope.settlement = function (item) {
                $scope.changeTab(5);
                $scope.orderObj.headerInfo = item;
                getReceiptTableList();
            };

            //获取收款单据列表
            function getReceiptTableList() {
                var service = "device",
                    reqUrl = "/arap/detailList",
                    param = {
                        filters: {
                            orgId: $scope.orderObj.headerInfo.purchaseOrgId,
                            type: 0,
                            isSettle: 0,
                            isAll: 1,
                            billNo: $scope.orderObj.headerInfo.deliveryNo
                        }
                    };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.billSingleF = $filter("orderType")(item.billSingle);
                        item.billDateF = $filter("YbDate")(item.billDate, df);
                        item.isChecked = false;
                        item.checkPrice = item.remainPrice;
                    });
                    $scope.receiptTableInfo.dataList = resp.value.list;
                });
            }


            //选择人员
            $scope.selectOperator = function () {
                var param = {
                    name: "调度员",
                    type: "staff",
                    supplierOrgId: ""
                };
                if ($scope.curUser) {
                    param.supplierOrgId = $scope.curUser.spaceId;
                    param.type = "staffByWorkspace";
                }
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.operatorId = data.userId;
                    $scope.orderObj.headerInfo.operatorName = data.name;
                })
            };
            $scope.auditBill = function (item) {
                $scope.auditId = item.id;
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(7);
                    $scope.forward = data.headerInfo.forward;
                    data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        item.invoiceFlagShow = $filter("TrueOrFalse")(item.invoiceFlag)
                        item.deliveryNum = item.deliveryNum - item.deliveryQty;
                        item.deliveryMax = item.amountAfterAdjust - item.sendQty + item.deliveryQty;
                        if (item.deliveryQty <= item.deliveryMax) {
                            checkItemStockStatus(item);
                        }
                    });
                });
            };

            $scope.auditData = function (auditType, Id) {
                var ids = [];

                if (auditType === "single") {
                    ids.push(Id);
                }
                if (auditType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            ids.push($scope.dataList[i].id);
                        }
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要审核的行');
                    return;
                }
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        var param = {
                            auditRemark: val,
                            ids: ids,
                        }
                        var service = "device";
                        var reqUrl = "/deliveryNote/auditPass";
                        return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                $scope.clickValue = false;
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                            $scope.changeTab(0);
                        })
                    },
                    refuseCb: function(val) {
                        var param = {
                            auditRemark: val,
                            ids: ids,
                        }
                        var service = "device";
                        var reqUrl = "/deliveryNote/auditReject";
                        return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                $scope.clickValue = false;
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                            $scope.changeTab(0);
                        })
                    }
                })
            };

            $scope.auditPass = function () {
                var service = "device";
                var reqUrl = "/deliveryNote/auditPass";
                var param = {};
                param.ids = [];
                param.ids.push($scope.auditId);
                param.auditRemark = $scope.orderObj.auditMessage;

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                    $scope.orderObj.auditMessage = "";
                });
            };
            $scope.auditReject = function () {
                var service = "device";
                var reqUrl = "/deliveryNote/auditReject";
                var param = {};
                param.ids = [];
                param.ids.push($scope.auditId);
                if($scope.orderObj.auditMessage == ''){
                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                }
                param.auditRemark = $scope.orderObj.auditMessage;

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                    $scope.orderObj.auditMessage = "";
                });
            };

            $scope.adjustBill = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(4);
                    $scope.forward = data.headerInfo.forward;
                    data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.materialList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        if (!item.status || item.status == 0 || item.status == 1) {
                          item.deliveryNum = item.deliveryNum - item.deliveryQty;
                        }
                        item.deliveryMax = item.amountAfterAdjust - item.sendQty + item.deliveryQty;
                        if (item.deliveryQty <= item.deliveryMax) {
                          if (item.status == 2 || item.status == 3) {
                            return;
                          }
                            checkItemStockStatus(item);
                        }
                    });
                });
            };

            $scope.adjustData = function () {
                var valid = true;
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    if (item.deliveryQty < item.inventoryOutAmount) {
                        valid = false;
                        item.qtyErr = true;
                        item.qtyErrMsg = "本次发货数量不能小于已出库数量";
                    }
                });
                if (!valid) {
                    return;
                }
                if ($scope.clickValue) {
                    return;
                }
                // 农机进行校验库存
                if ($scope.isNJ && isErrorStockStatusForExcavatorCompany()) {
                  return;
                }
                $scope.clickValue = true;
                var service = "device";
                var reqUrl = "/deliveryNote/adjust";
                $scope.detailInfo.headerInfo.forward = $scope.forward
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        $scope.clickValue = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.clickValue = false;
                    getDataList();
                    $scope.changeTab(0);
                });
            };

            $scope.printSingle = function (item) {
                var param = {
                    printType: "SaleOrder",
                    cusParam: { ids: [item.id] }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.batchPrint = function () {
                const billIds = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "SaleOrder",
                    cusParam: { ids: billIds }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            function checkNumValid() {
                var valid = true;
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    if (!$scope.isWJ && (!item.deliveryQty || item.deliveryQty == "0" || parseFloat(item.deliveryQty) <= 0)) {
                        valid = false;
                        item.qtyErr = true;
                        item.qtyErrMsg = "发货数量不能为空和0";
                        return;
                    }
                    if (item.deliveryQty > item.deliveryMax) {
                        valid = false;
                        item.qtyErr = true;
                        item.qtyErrMsg = "发货数量不能超过允许数量";
                    }
                });
                return valid;
            }

            $scope.clickValue = false;

            $scope.submitData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.clickValue) {
                    return;
                }
                $scope.clickValue = true;
                if ($scope.detailInfo.materialList.length === 0) {
                    $scope.clickValue = false;
                    ybWidget.ShowToaster('error', '请选择零件');
                    return;
                }
                if (!checkNumValid()) {
                    $scope.clickValue = false;
                    return;
                }
                var msg = checkPrice();
                if (msg !== '0') {
                    $scope.clickValue = false;
                    ybWidget.ShowToaster('error', msg);
                    return;
                }
                if (isErrorStockStatusForExcavatorCompany()) {
                    return;
                }
                var service = "device";
                var reqUrl = "/deliveryNote/submit";
                var param = {};
                param = $scope.detailInfo;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        $scope.clickValue = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                    $scope.clickValue = false;
                });
            };

            function isErrorStockStatusForExcavatorCompany() {
                // 暂时 农机使用这种配置
                if ($scope.isNJ) {
                  if (!UserContextService.NeedCheckStockQty('发货通知单', $scope.curOrgId)) {
                    return false;
                  }
                } else {
                    if (!($scope.isWJ || $scope.isKJ || $scope.isJCH || $scope.isNY)) {
                      return false;
                    }
                }

                for (var i = 0; i < $scope.detailInfo.materialList.length; i++) {
                    if ($scope.detailInfo.materialList[i].status == 2 || $scope.detailInfo.materialList[i].status == 3) {
                      continue;
                    }
                    checkItemStockStatus($scope.detailInfo.materialList[i]);
                    
                    // 农机默认校验库存
                    // 没有该权限(deliveryTJSC)，校验库存
                    if ($scope.isNJ || !$scope.btnPermission.deliveryTJSC) {
                        if ($scope.detailInfo.materialList[i].qtyStockErr && ($scope.detailInfo.materialList[i].qtyStockErrLevel > 1)) {
                            ybWidget.ShowMessage("零件" + $scope.detailInfo.materialList[i].materialsNo + "，" + $scope.detailInfo.materialList[i].materialsDes + "库存不足，单据不能创建，请先删除该零件或取消提交", MESG_TYPE.Error);
                            $scope.clickValue = false;
                            return true;
                        }
                    }
                }
                return false;

            }

            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    item.showStockErr = true;
                }
            };

            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };

            $scope.checkQty = function (item) {
                item.qtyErr = false;
                item.qtyStockErr = false;
                if (!$scope.isWJ && (!item.deliveryQty || item.deliveryQty == "0" || parseFloat(item.deliveryQty) <= 0)) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "发货数量不能为空和0";
                    return;
                }
                if (item.deliveryQty > item.deliveryMax) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "发货数量不能超过允许数量";
                    return;
                }
                if ($scope.activeFlag[4]) {
                    if (item.deliveryQty < item.inventoryOutAmount) {
                        item.qtyErr = true;
                        item.qtyErrMsg = "本次发货数量不能小于已出库数量";
                        return;
                    }
                }
                checkItemStockStatus(item);
            };

            function checkItemStockStatus(item) {
                UserContextService.SetStockStatusFlag(item, item.deliveryQty);

            }

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.clickValue) {
                    return;
                }
                $scope.clickValue = true;
                if ($scope.detailInfo.materialList.length == 0) {
                    ybWidget.ShowMessage('发货通知单必须有零件');
                    $scope.clickValue = false;
                    return;
                }
                if (!checkNumValid()) {
                    // ybWidget.ShowMessage('本次发货数超过允许数量');
                    $scope.clickValue = false;
                    return;
                }
                var msg = checkPrice();
                if (msg !== '0') {
                    $scope.clickValue = false;
                    ybWidget.ShowToaster('error', msg);
                    return;
                }
                if (isErrorStockStatusForExcavatorCompany()) {
                    return;
                }
                var service = "device";
                var reqUrl = "/deliveryNote/add";
                var param = {};
                param = $scope.detailInfo;
                param.billId = $scope.detailInfo.id;
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/deliveryNote/update";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        $scope.clickValue = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                    $scope.clickValue = false;
                });
            };

            function checkPrice() {
                var num = 0;
                var msg = '0';
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    if (!!item.unitPriceAfterAdjust) {
                        num += 1;
                    }
                });
                if ($scope.detailInfo.materialList.length > num && num > 0) {
                    msg = '有价格和无价格的零件不能同时出现在一个发货通知单';
                }
                return msg;
            }

            $scope.outbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    data.headerInfo.forward = $filter("TrueOrFalse")(data.headerInfo.forward);
                    angular.forEach(data.materialList, function (obj) {
                      obj.estimatedShippingDateShow = $filter("YbDate")(obj.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                      if (($scope.isJCH || $scope.isNJ) && obj.stockLocation && (obj.status == 0 || obj.status == 1)) {
                        const splits = obj.stockLocation.split('-');
                        obj.locationCode = obj.stockLocation;
                        obj.warehouseCode = splits[splits.length -1];
                        obj.areaCode = splits[splits.length -2];
                      }
                    })
                    $scope.detailInfo = data;
                    $scope.changeTab(3);
                });
            };

            $scope.revokeOutbound = function(item) {
                ybWidget.ShowMessage("确定要撤回出库吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', '/warehouseInventory/deliveryAllRevoke', { businessOrder: item.deliveryNo }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            $scope.outboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.deliveryNo;
                angular.forEach($scope.detailInfo.materialList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    param.detailList.push(listRow);
                });
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };


            $scope.saveAddReceipt = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }

                var param = {
                    headerInfo: {}
                };
                var service = "device";
                var reqUrl = "/check/add";
                param.headerInfo.discountPrice = $scope.orderObj.headerInfo.discountPrice || 0;
                param.headerInfo.checkType = 0;
                param.headerInfo.supplierOrgId = $scope.curOrgId;
                param.headerInfo.supplierOrgName = $scope.curOrg.companyName;
                param.headerInfo.purchaseOrgId = $scope.orderObj.headerInfo.purchaseOrgId;
                param.headerInfo.purchaseOrgName = $scope.orderObj.headerInfo.purchaseOrgName;
                param.headerInfo.operatorId = $scope.orderObj.headerInfo.operatorId;
                param.headerInfo.operatorName = $scope.orderObj.headerInfo.operatorName;
                param.headerInfo.note = $scope.orderObj.headerInfo.note;
                param.headerInfo.settleType = 0;
                param.headerInfo.isDealer = 1;
                param.headerInfo.totalPrice = $scope.orderObj.headerInfo.totalDiscountPrice;
                param.detailList = [];
                angular.forEach($scope.receiptTableInfo.dataList, function (item) {
                    param.detailList.push({
                        arapDetailId: item.id,
                        billDate: item.billDate,
                        billNo: item.billNo,
                        billId: item.billId,
                        billSingle: item.billSingle,
                        checkPrice: item.checkPrice,
                        totalPrice: item.totalPrice,
                        receivePrice: item.remainPrice
                    });

                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };

            /**
             * ***************************************** 单据详情 开始 *****************************************
             */
            $scope.orderDetailObj = {};
            $scope.orderDetailTableInfo = {
                markInfo: {
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 1270,
                    tableCol: [{
                            name: "零件编号",
                            dataField: "materialsNo",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "零件中文名",
                            dataField: "materialsDes",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "单位",
                            dataField: "unit",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "默认储位",
                            dataField: "stockLocation",
                            width: 150,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "订单总数",
                            dataField: "amountAfterAdjust",
                            width: 80,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "已发数量",
                            dataField: "sendQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "本次发货",
                            dataField: "deliveryQty",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "单价",
                            dataField: "unitPriceAfterAdjust",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "已出库数",
                            dataField: "inventoryOutAmount",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "实际库存",
                            dataField: "enableNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "意向占用",
                            dataField: "intentionNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            clickFn: "intentionDetail",
                            toSort: false
                        },
                        {
                            name: "发货占用",
                            dataField: "deliveryNum",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            clickFn: "deliveryDetail",
                            toSort: false
                        },
                        {
                            name: "安全库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        },
                        {
                            name: "危险库存",
                            dataField: "logState",
                            width: 100,
                            isShow: true,
                            isFixed: false,
                            toSort: false
                        }
                    ]
                },
                dataList: []
            };
            //xbt
            function viewOrderDetail(item) {
                switch (item.billSingle) {
                    case "XGFT":
                        $scope.orderDetailObj = {};
                        $scope.orderDetailTableInfo.dataList = [];
                        getXGFTOrderDetail(item.billId).then(function (data) {
                            if (!data) {
                                return;
                            }
                            $scope.orderDetailObj = data.headerInfo;
                            $scope.orderDetailTableInfo.dataList = data.materialList;
                            $scope.changeTab(6);
                        });
                        break;
                    default:
                        break;
                }

            }

            function getXGFTOrderDetail(billId) {
                var service = "device";
                var reqUrl = "/deliveryNote/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }

                    return resp.value;
                });
            }

            /**
             * ***************************************** 单据详情 结束 *****************************************
             */

            $scope.readyOpr = function (billId, type) {
                var service = "device";
                var reqUrl = "/deliveryNote/updateIsReady";
                var billIds = [];

                if (type === "single") {
                    billIds.push(billId);
                }

                if (type === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }

                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要就绪的行');
                    return;
                }
                ybWidget.ShowMessage("确定要执行就绪操作吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };


            $scope.sapStockMap = {}

            function pickingBillMaterialChange(item) {
                // 处理大厂库存逻辑
                // 仅限基础、能源
                if (!$scope.isJCH && !$scope.isNY) return
                var service = 'device';
                var reqUrl = '/materialsSchedule/sapStock';
                var param = {
                    materialsNo: item.materialsNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sapStockMap[item.materialsNo] = resp.value || {}
                    item.totalStock = resp.value?.totalStock
                });
            }

            function dachangStock(item) {
                var param = {
                    title: '大厂库存',
                    data: item.detailVOList || []
                };
                ybWidget.DatasShow(param);
            }


            /**
             * ***************************************** 大厂库存  结束 *****************************************
             */


            $scope.printBill4Details = function (item) {
                handlePrint4Details([item]);
            };

            $scope.batchPrint4Details = function () {
                const selectedDatas4Detail = $scope.detailInfo.materialList.filter(d => d.isChecked);
                if (selectedDatas4Detail.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                handlePrint4Details(selectedDatas4Detail);
            };

            $scope.selectAgent = function () {
                var param = {
                    name: "所属办事处",
                    type: "agency"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    // console.log(data)
                   $scope.detailInfo.headerInfo.agency = data.name
                })
            };

            function handlePrint4Details(data) {
                const { headerInfo } = angular.copy($scope.detailInfo);
                var param = {
                    printType: "SaleOrder",
                    printDataInfo: [{ headerInfo, materialList: data }]
                };
                ybWidget.SetIsPrintOrPreview(param);
            }
            function getTJJXType(){
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var param = {pCode:"TJJX"};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.TJJXList =resp.value;
                });
            }

            (function () {
                getAencyList();
                getTJJXType()
                $scope.storageKey = $state.current.name;
                UserContextService.LocalCache($scope.storageKey, $scope.condition);

                if (!!$stateParams.id) {
                    $scope.changeTab(1);
                    $scope.tabFlag.type = 0;
                    $scope.tabFlag.name = tabFlag[0];
                    $scope.orderSelectSingle($stateParams.id);
                }

                // 如果从首页代办事项发货通知单预警按钮跳转过来就将高级搜索条件的发货通知单预警选项设为是
                if ($stateParams.flag){
                    console.log("从首页代办事项的发货通知单预警跳转过来的");
                    $scope.condition.notCompletedForOver7DaysCond = 1;
                    $scope.condition.createName = $scope.curUser.name;
                    getDataList();
                }

                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
